package com.lyc.demo;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;

import java.util.Map;

@Slf4j
public class JsonToMap {

    private String json;

    /**
     * 将map对象转换成json
     */
    @Before
    public void testMapToJson(){
        User user1 = User.builder()
                .id(1)
                .name("zhangsan")
                .build();
        User user2 = User.builder()
                .id(2)
                .name("lisi")
                .build();
        Map<String,User> map = Maps.newHashMap();
        map.put("user1",user1);
        map.put("user2",user2);
        json = JsonMapper.objectToJson(map);
    }

    /**
     * 将json转换成map对象（TypeReference）
     */
    @Test
    public void testJsonToMapTypeReference(){
        Map<String,User> map = JsonMapper.jsonToObject(json, new TypeReference<Map<String,User>>() {
        });
        if(map != null){
            User user1 = map.get("user1");
            User user2 = map.get("user2");
            log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
            log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
        }
    }

    /**
     * 将json转换成mao对象（Class）
     */
    @Test
    public void testJsonToMapClass(){
        Map<String,User> map = JsonMapper.jsonToObject(json, Map.class,String.class,User.class);
        if(map != null){
            User user1 = map.get("user1");
            User user2 = map.get("user2");
            log.info("user1.id = " + user1.getId() + ",user1.name = " + user1.getName());
            log.info("user2.id = " + user2.getId() + ",user2.name = " + user2.getName());
        }
    }
}
